package com.ycy.temperature.view.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.gigamole.infinitecycleviewpager.HorizontalInfiniteCycleViewPager;
import com.jude.utils.JUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.ycy.temperature.R;
import com.ycy.temperature.adapter.AuthenticationViewAdapter;
import com.ycy.temperature.adapter.HorizontalPagerAdapter;
import com.ycy.temperature.adapter.ViewPagerAdapter;
import com.ycy.temperature.bean.AuthenticationBean;
import com.ycy.temperature.bean.ＭeBean;
import com.ycy.temperature.date.net.UserNetWorks;
import com.ycy.temperature.date.utils.CheckUtils;
import com.ycy.temperature.date.utils.Utils;
import com.ycy.temperature.view.activity.EducationActivity;
import com.ycy.temperature.view.activity.HeadPortraitActivity;
import com.ycy.temperature.view.activity.HouseActivity;
import com.ycy.temperature.view.activity.OccupationActivity;
import com.ycy.temperature.view.activity.OtherActivity;
import com.ycy.temperature.view.activity.RechargeActivity;
import com.ycy.temperature.view.activity.SetUpActivity;
import com.ycy.temperature.view.activity.VehicleActivity;
import com.ycy.temperature.view.base.BaseFragment;
import com.zhy.autolayout.AutoLinearLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import rx.Subscriber;

/**
 * Created by MI on 2018/7/17.
 */

public class MeFragment extends BaseFragment {
    @BindView(R.id.Layout_Schedule)
    AutoLinearLayout LayoutSchedule;
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    Unbinder unbinder;
    List<AuthenticationBean> authenticationBean;
    int pageCount;//总页数
    int pageSize = 3;//每一页的个数
    int curIndex = 0;
    LayoutInflater inflater;
    List<View> mPagerList;
    @BindView(R.id.Layout_Height)
    AutoLinearLayout LayoutHeight;
    @BindView(R.id.Layout_Interest)
    AutoLinearLayout LayoutInterest;
    @BindView(R.id.Layout_Occupation)
    AutoLinearLayout LayoutOccupation;
    @BindView(R.id.Layout_Education)
    AutoLinearLayout LayoutEducation;

    @BindView(R.id.Image_Direction)
    ImageView ImageDirection;
    @BindView(R.id.Image_Head)
    ImageView ImageHead;
    @BindView(R.id.Image_PhotoWall)
    ImageView ImagePhotoWall;


    @BindView(R.id.Text_NickName)
    TextView TextNickName;
    @BindView(R.id.Text_Autograph)
    TextView TextAutograph;
    @BindView(R.id.Text_Age)
    TextView TextAge;
    @BindView(R.id.Text_Nativeplace)
    TextView TextNativeplace;
    @BindView(R.id.Text_Nationality)
    TextView TextNationality;
    @BindView(R.id.Text_City)
    TextView TextCity;
    @BindView(R.id.Text_Marriage)
    TextView TextMarriage;
    @BindView(R.id.Text_Children)
    TextView TextChildren;
    @BindView(R.id.Text_Height)
    TextView TextHeight;
    @BindView(R.id.Text_Hobby)
    TextView TextHobby;
    @BindView(R.id.Text_Activity)
    TextView TextActivity;
    @BindView(R.id.Text_Dynamic)
    TextView TextDynamic;

    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;

    DynamicMeFragment dynamicFragment;
    ActivityMeFragment activityFragment;

    Handler mHandler = new Handler(Looper.getMainLooper());
    boolean Open = true;
    String StrPage = "1";

    Utils.LibraryObject[] LIBRARIES = new Utils.LibraryObject[]{
            new Utils.LibraryObject(
                    R.drawable.ic_strategy,
                    "Strategy"
            ),
            new Utils.LibraryObject(
                    R.drawable.ic_design,
                    "Design"
            ),
            new Utils.LibraryObject(
                    R.drawable.ic_development,
                    "Development"
            ),
            new Utils.LibraryObject(
                    R.drawable.ic_qa,
                    "Quality Assurance1"
            ),
            new Utils.LibraryObject(
                    R.drawable.ic_qa,
                    "Quality Assurance2"
            ),
            new Utils.LibraryObject(
                    R.drawable.ic_qa,
                    "Quality Assurance3"
            )
    };

    @Override
    protected int getRes() {
        return R.layout.fragment_me;
    }

    @Override
    protected void init(View view) {
        unbinder = ButterKnife.bind(this, view);
        getPersonal();
        authenticationBean = new ArrayList<AuthenticationBean>();
        inflater = LayoutInflater.from(getActivity());
        dynamicFragment = new DynamicMeFragment();
        activityFragment = new ActivityMeFragment();
        getChildFragmentManager().beginTransaction().add(R.id.Layout_Page, activityFragment).disallowAddToBackStack().commit();
        getChildFragmentManager().beginTransaction().add(R.id.Layout_Page, dynamicFragment).disallowAddToBackStack().show(dynamicFragment).commit();
        dynamicFragment.hide();
        getsmartRefreshLayout();
    }

    @Override
    protected void setData(View view) {

    }

    @Override
    public void onClick(View v) {

    }

    @OnClick({R.id.Image_Direction, R.id.Image_SetUp, R.id.Image_Data, R.id.Button_Recharge, R.id.Text_Activity, R.id.Text_Dynamic})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.Image_Direction:
                if (Open) {
                    Open = false;
                    LayoutHeight.setVisibility(View.VISIBLE);
                    LayoutInterest.setVisibility(View.VISIBLE);
                    LayoutOccupation.setVisibility(View.VISIBLE);
                    LayoutEducation.setVisibility(View.VISIBLE);
                    ImageDirection.setImageResource(R.mipmap.image_upper);
                } else {
                    Open = true;
                    LayoutHeight.setVisibility(View.GONE);
                    LayoutInterest.setVisibility(View.GONE);
                    LayoutOccupation.setVisibility(View.GONE);
                    LayoutEducation.setVisibility(View.GONE);
                    ImageDirection.setImageResource(R.mipmap.image_lower);
                }
                break;
            case R.id.Image_SetUp:
                startActivity(new Intent(getActivity(), SetUpActivity.class));
                break;
            case R.id.Image_Data:
                startActivity(new Intent(getActivity(), OtherActivity.class));
                break;
            case R.id.Button_Recharge:
                startActivity(new Intent(getActivity(), RechargeActivity.class));
                break;
            case R.id.Text_Activity:
                StrPage = "1";
                showFragment(activityFragment);
                TextActivity.setTextColor(TextActivity.getResources().getColor(R.color.bg_Blue));
                TextDynamic.setTextColor(TextDynamic.getResources().getColor(R.color.tx_Gray));
                break;
            case R.id.Text_Dynamic:
                StrPage = "2";
                TextDynamic.setTextColor(TextActivity.getResources().getColor(R.color.bg_Blue));
                TextActivity.setTextColor(TextDynamic.getResources().getColor(R.color.tx_Gray));
                showFragment(dynamicFragment);
                break;

        }
    }

    @Override
    public void onViewCreated(final View view, @Nullable final Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        final HorizontalInfiniteCycleViewPager horizontalInfiniteCycleViewPager =
                (HorizontalInfiniteCycleViewPager) view.findViewById(R.id.hicvp);
        horizontalInfiniteCycleViewPager.setAdapter(new HorizontalPagerAdapter(getContext(), true, LIBRARIES));
    }

    public void showFragment(Fragment showFragemt) {
        hideFrags();
        getChildFragmentManager().beginTransaction().disallowAddToBackStack().show(showFragemt).commit();
    }

    public void hideFrags() {
        dynamicFragment.hide();
        activityFragment.hide();
    }

    public void getsmartRefreshLayout() {
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (StrPage.equals("1")) {
                            activityFragment.i = 0;
                            activityFragment.setActivity("0");
                            refreshLayout.finishRefresh();
                        } else if (StrPage.equals("2")) {
                            dynamicFragment.i = 0;
                            dynamicFragment.setDynamic("0");
                            refreshLayout.finishRefresh();
                        }
                    }
                }, 2000);
            }
        });
        smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (StrPage.equals("1")) {
                            activityFragment.setActivity(activityFragment.i + "");
                            refreshLayout.finishLoadMore();
                        } else if (StrPage.equals("2")) {
                            dynamicFragment.setDynamic(dynamicFragment.i + "");
                            refreshLayout.finishLoadMore();
                        }
                    }
                }, 2000);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    private void setOvalLayout() {
        for (int i = 0; i < pageCount; i++) {
            LayoutSchedule.addView(inflater.inflate(R.layout.dot, null));
        }
        //默认显示第一页
        LayoutSchedule.getChildAt(0).findViewById(R.id.v_dot).setBackgroundResource(R.drawable.dot_ture);
        viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //取消选中
                LayoutSchedule.getChildAt(curIndex).findViewById(R.id.v_dot).setBackgroundResource(R.drawable.dot_false);
                //选中
                LayoutSchedule.getChildAt(position).findViewById(R.id.v_dot).setBackgroundResource(R.drawable.dot_ture);

                curIndex = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    public void getPersonal() {
        UserNetWorks.getMeData("aa", new Subscriber<ＭeBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                JUtils.Toast("网络错误");
            }

            @Override
            public void onNext(ＭeBean ｍeBean) {
                if (ｍeBean.getResponseState().equals("1")) {
                    if (!CheckUtils.isEmpty(ｍeBean.getData().getHeadimage())) {
                        Glide.with(getActivity()).load("http://" + ｍeBean.getData().getHeadimage()).into(ImageHead);
                    }
                    if (!CheckUtils.isEmpty(ｍeBean.getData().getNickname())) {
                        TextNickName.setText(ｍeBean.getData().getNickname());
                    }
                    if (!CheckUtils.isEmpty(ｍeBean.getData().getAutograph())) {
                        TextAutograph.setText(ｍeBean.getData().getAutograph());
                    }
                    if (!CheckUtils.isEmpty(ｍeBean.getData().getHeadimage())) {
                        Glide.with(getActivity()).load("http://" + ｍeBean.getData().getPhotowall()).into(ImagePhotoWall);
                    }
                    if (!CheckUtils.isEmpty(ｍeBean.getData().getAge())) {
                        TextAge.setText(ｍeBean.getData().getAge());
                    }
                    if (!CheckUtils.isEmpty(ｍeBean.getData().getNativeplace())) {
                        TextNativeplace.setText(ｍeBean.getData().getNativeplace());
                    }
                    if (!CheckUtils.isEmpty(ｍeBean.getData().getNationality())) {
                        TextNationality.setText(ｍeBean.getData().getNationality());
                    }
                    if (!CheckUtils.isEmpty(ｍeBean.getData().getCity())) {
                        TextCity.setText(ｍeBean.getData().getCity());
                    }
                    if (!CheckUtils.isEmpty(ｍeBean.getData().getMarriage())) {
                        TextMarriage.setText(ｍeBean.getData().getMarriage());
                    }
                    if (!CheckUtils.isEmpty(ｍeBean.getData().getChildren())) {
                        TextChildren.setText(ｍeBean.getData().getChildren());
                    }
                    if (!CheckUtils.isEmpty(ｍeBean.getData().getHeight())) {
                        TextHeight.setText(ｍeBean.getData().getHeight());
                    }
                    if (!CheckUtils.isEmpty(ｍeBean.getData().getHobby())) {
                        TextHobby.setText(ｍeBean.getData().getHobby());
                    }
                    authenticationBean.clear();
                    authenticationBean.add(new AuthenticationBean("头像认证", "Authentication", ｍeBean.getData().getAuthenticationHeadimageState()));
                    authenticationBean.add(new AuthenticationBean("学历认证", "Education", ｍeBean.getData().getAuthenticationEducationState()));
                    authenticationBean.add(new AuthenticationBean("职业认证", "Occupation", ｍeBean.getData().getAuthenticationJobState()));
                    authenticationBean.add(new AuthenticationBean("车辆认证", "Vehicle", ｍeBean.getData().getAuthenticationCarState()));
                    authenticationBean.add(new AuthenticationBean("房产认证", "HouseProperty", ｍeBean.getData().getAuthenticationHouseState()));
                    //总页数=总数/每页的个数，取整
                    pageCount = (int) Math.ceil(authenticationBean.size() * 1.0 / pageSize);

                    mPagerList = new ArrayList<>();
                    for (int i = 0; i < pageCount; i++) {
                        //每个页面都是inflate出的一个新实例
                        GridView gridView = (GridView) inflater.inflate(R.layout.gridview_authentication, null);
                        gridView.setAdapter(new AuthenticationViewAdapter(getActivity(), authenticationBean, i, pageSize));
                        mPagerList.add(gridView);
                        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                int pos = position + curIndex * pageSize;
                                if (pos == 0) {
                                    if (authenticationBean.get(pos).getAuthentication().equals("0")) {
                                        startActivity(new Intent(getActivity(), HeadPortraitActivity.class));
                                    }
                                } else if (pos == 1) {
                                    if (authenticationBean.get(pos).getAuthentication().equals("0")) {
                                        startActivity(new Intent(getActivity(), EducationActivity.class));
                                    }
                                } else if (pos == 2) {
                                    if (authenticationBean.get(pos).getAuthentication().equals("0")) {
                                        startActivity(new Intent(getActivity(), OccupationActivity.class));
                                    }
                                } else if (pos == 3) {
                                    if (authenticationBean.get(pos).getAuthentication().equals("0")) {
                                        startActivity(new Intent(getActivity(), VehicleActivity.class));
                                    }
                                } else if (pos == 4) {
                                    if (authenticationBean.get(pos).getAuthentication().equals("0")) {
                                        startActivity(new Intent(getActivity(), HouseActivity.class));
                                    }
                                }
                            }
                        });
                    }
                    //设置viewpageAdapter
                    viewpager.setAdapter(new ViewPagerAdapter(mPagerList));
                    //设置小圆点
                    setOvalLayout();
                }
            }
        });
    }

}
